//物料管理
angular.module('SmartCanteenApp.materiel', ['ngRoute', 'ngTouch','ui.tree'])

	.config(['$routeProvider', function($routeProvider) {
		$routeProvider.when('/materiel', {
			templateUrl: 'materielManage/materielManage.html',
			controller: 'materielManageCtrl'
		});
		$routeProvider.when('/newMateriel', {
			templateUrl: 'materielManage/newMateriel.html',
			controller: 'newMaterielCtrl'
		});
	}])

	.controller('materielManageCtrl', ['$scope', '$timeout', function($scope, $timeout) {
		$scope.hideCanteen()
		$(".modal-dialog").draggable();//为模态对话框添加拖拽
	    $(".modal").css("overflow", "hidden");//禁止模态对话框的半透明背景滚动
	    //获取工序 车间 负责人
	    $scope.getSelectData = function(){
	    	//请求所用工序
			$scope.getJson($scope.resultPath+'/wisdomeatery/v1/product_plan/canteens/'+$scope.canteenId+'/procedures','','get',function(data){
				$scope.procedure = data.data
				console.log(data)
			})
			//请求当前食堂下的所有员工
			$scope.getJson($scope.resultPath+'/wisdomeatery/v1/base_system/canteens/'+$scope.canteenId+'/employees','','get',function(data){
				$scope.workshop_leader = data.data
			})
			//请求所有车间
			$scope.getJson($scope.resultPath+'/wisdomeatery/v1/base_system/canteens/'+$scope.canteenId+'/workshops','','get',function(data){
				$scope.workshop = data.data
			})
			//请求所有分类（半成品和原料）
			$scope.getJson($scope.resultPath+'/wisdomeatery/v1/canteens/'+$scope.canteenId+'/materialCategories','','get',function(data){
				$scope.allAllCategorys = data.data
				console.log(data)
			})
//			$scope.chefs = [
//					{
//						"name":"厨师1",
//						"id":1
//					},
//					{
//						"name":"厨师2",
//						"id":2
//					},
//				]
			//获取所有厨师
			$scope.getJson($scope.resultPath+'/wisdomeatery/v1/menus/canteens/'+$scope.canteenId+'/chief','','get',function(data){
				$scope.chefs = data.data
				console.log(data)
			})
	    }
	    //获取全部大分类
	    $scope.getFinalCategorys = function(){
   				$scope.getJson($scope.resultPath+'/wisdomeatery/v1/canteens/'+$scope.canteenId+'/processing_material_categorys','','get',function(data){
					console.log(data)
					$scope.bigCategorys = data.data
				})
   		}
	    $scope.yyyy = function(){
	    	console.log($scope.chefs)
	    }
   		//获取全部半成品
   		$scope.getMateriels = function(){
   			$scope.getJson($scope.resultPath+'/wisdomeatery/v1/canteens/'+$scope.canteenId+'/processing_materials','','get',function(data){
					console.log(data)
					$scope.materiels = data.data
					$scope.staticMateriels =data.data.concat()
//					copy(data.data,$scope.staticMateriels)
					
			})		
   		}
   		//获取全部单位
		$scope.getUnits = function(){
			$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/itemsUnit",'',"GET",function(data){
				console.log(data)
				$scope.units = data.data
			})
		}
   		//获取全部原料和半成品
   		var allsonsMateriels
   		$scope.getAllsons = function(level){
   			let levelPath = ''
   			console.log(level)
   			if(level == 'new'){
   				levelPath = ''
   			}else{
   				levelPath = '?level='+level
   			}
   			$scope.getJson($scope.resultPath+'/wisdomeatery/v1/canteens/'+$scope.canteenId+'/processing_materials_total','','get',function(data){
   				console.log($scope.resultPath+'/wisdomeatery/v1/canteens/'+$scope.canteenId+'/processing_materials_total')
   				$scope.sonsMateriels = data.data
   				allsonsMateriels = data.data.concat()
   				console.log($scope.sonsMateriels)
   			})
   		}
   		//原料模糊搜索
   		$scope.$watch('searchMaterie', function() {
			if($scope.searchMaterie == undefined) {
				$scope.searchMaterie = '';
			}
			//准备一个空的数组
			var newList = [];
			var arr = allsonsMateriels;
			if(arr == undefined)
				return
			
			var length = allsonsMateriels.length;
			console.log(allsonsMateriels)
			for(var i = 0; i < length; i++) {
				if(arr[i].name.indexOf($scope.searchMaterie) >= 0 ) {
					newList.push(arr[i]);
				}
			}
	
			/*     $scope.pagination(newList);*/
			$scope.sonsMateriels = newList

		});
   		if( $scope.getCanteenId() != ''){
   				$scope.canteenId =  $scope.getCanteenId() ;
   				//获取某食堂下所有分类
		 		$scope.getFinalCategorys();
		 		//获取所有菜品
		 		$scope.getMateriels();
		 		//获取车间 负责人 工序
		 		$scope.getSelectData();
		 		//获取单位
		 		$scope.getUnits()
   		}
		$scope.$on('to-child', function(event,data) {
		   	console.log($scope.getId);
			//获取从父控制器传来的当前选中食堂
			$scope.canteenId = data;
			console.log($scope.canteenId);
			//获取所有分类
			$scope.getFinalCategorys();
			//获取所有物料
			$scope.getMateriels();
			//获取车间 负责人 工序
		 	$scope.getSelectData();
		 	//获取所有单位
		 	$scope.getUnits()
		});
		//监听物料搜索框
		$scope.$watch('searchMaterie', function() {
			if($scope.searchMaterie == undefined) {
				$scope.searchMaterie = '';
			}
			//准备一个空的数组
			var newList = [];
			var arr = $scope.staticMateriels;
			if(arr == undefined)
				return
			
			var length = arr.length;
	
			for(var i = 0; i < length; i++) {
				if(arr[i].name.indexOf($scope.searchMaterie) >= 0 ) {
					newList.push(arr[i]);
				}
			}
	
			$scope.materiels = newList
	
		});		
		//点击大分类筛选其下子分类 并改变样式
		$scope.searchMateriel = function(e,id){
			$('.bigC').removeClass('activeLi')
			$(e.target).parent().addClass('activeLi')
			$scope.selectBigCiD = id
		}
		//取消筛选 查看全部物料
		$scope.showAllM = function(){
			$('.bigC').removeClass('activeLi')
			$scope.selectBigCiD = undefined
		}
		//保存新增类别
		$scope.newBigC = {
			"name":""
		}
		$scope.saveNewBigC = function(){
			if($scope.newBigC.name == '' || $scope.newBigC.name == undefined){
				$scope.showError('名称不能为空')
				return
			}
			$scope.getJson($scope.resultPath+'/wisdomeatery/v1/canteens/'+$scope.canteenId+'/processing_material_categorys',$scope.newBigC,'post',function(data){
				if(data.code == 0){
					$('#newBigC').modal('toggle')
					$scope.newBigC.name=''
					//获取所有分类
					$scope.getFinalCategorys();
					$scope.showSuccess()
				}else{
					$scope.showError(data.msg)
				}
			})
			console.log($scope.newBigC)
		}
		//修改类别
		$scope.editC = {
			"name":'',
			"id":''
		}
		$scope.editBigC = function(name,id,e){
			e.preventDefault()
			e.stopPropagation();
			$scope.editC.name = name
			$scope.editC.id = id
			$('#editBigC').modal('toggle')
		}
		//提交修改
		$scope.sureEditBigC = function(){
			console.log($scope.editC)
			if($scope.editC.name == undefined){
				$scope.showError('名称不能为空')
				return
			}
			let id = $scope.editC.id
			delete $scope.editC.id
			$scope.getJson($scope.resultPath+'/wisdomeatery/v1/canteens/'+$scope.canteenId+'/processing_material_categorys/'+id,$scope.editC,'put',function(data){
				if(data.code == 0){
					$('#editBigC').modal('toggle')
					//获取所有分类
					$scope.getFinalCategorys();
					$scope.showSuccess()
				}else{
					$scope.showError(data.msg)
				}
			})
		}
		//删除模态框调出
		$scope.delBigC = function(data,e){
			e.preventDefault()
			e.stopPropagation();
			$scope.delBigCData = data
			$('#delBigC').modal('toggle')
		}
		//提交删除
		$scope.sureDelBigC = function(){
			//根据ID调用接口 查询其下子项 若子项大于0 return 不允许删除
			console.log($scope.delBigCData.id)
			$scope.getJson($scope.resultPath+'/wisdomeatery/v1/canteens/'+$scope.canteenId+'/processing_material_categorys/'+$scope.delBigCData.id,'','delete',function(data){
				if(data.code == 0){
					$('#delBigC').modal('toggle')
					//获取所有分类
					$scope.getFinalCategorys();
					$scope.showSuccess
				}else{
					$scope.showError(data.msg)
				}
			})
			
		}
	//物料操作
		//增加物料
		$scope.newMData = {
			"name": "",
			"category_id": "",
			"material_unit_id": "",
			"workshop_id": "",
			"procedure_id": "",
			"work_time": 0,
			"base_unit_value": 0,
			"detail": [],
			"remarks":'',
			"unit_id":null,
			"chef_id":""
		}
		$scope.newSonM = function(name,id,e){
			e.preventDefault()
			e.stopPropagation();
			$scope.textareaData = []
			$scope.modalName = name
			$scope.modalId = id    //向id为id的类别中添加半成品
			//清空选择标准成分的已选容器 显示所有项目
			if($scope.editMData != undefined){
				$scope.editMData.id = undefined
				$scope.selectM = []
				$scope.editMData.level = undefined
			}
			$scope.getAllsons('new')
			$('#newSonM').modal('toggle')
		}
		//取消新增物料
		$scope.cancleNewM = function(){
			$scope.newMData = {
				"name": "",
				"category_id": "",
				"material_unit_id": "",
				"workshop_id": "",
				"procedure_id": "",
				"work_time": 0,
				"base_unit_value": 0,
				"detail": [],
				"remarks":'',
				"unit_id":null
			}
			$scope.selectM = []
		}
		//保存新增的物料
		$scope.saveNewMaterie = function(){
			$scope.newMData.detail = $scope.selectM
			$scope.newMData.category_id = $scope.modalId
			console.log($scope.newMData)
			let n = $scope.newMData
			//判断非空调件
			if(n.name == '' ||n.name ==undefined ||n.procedure_id == '' || n.workshop_id == '' ||n.work_time<0 || n.detail == undefined || n.detail.length<1 || n.work_time == undefined || n.net_ratio == undefined 
				|| n.unit_id == null || n.unit_id == undefined){
				$scope.showError('请检查信息完整度')
				return
			}
			var workTimeStr = n.work_time
			console.log(checkNumber(workTimeStr))
			if(!checkNumber(workTimeStr)){
				$scope.showError('请填写正确加工时长')
				return
			}
			console.log($scope.newMData)
			$scope.getJson($scope.resultPath+'/wisdomeatery/v1/canteens/'+$scope.canteenId+'/processing_materials',$scope.newMData,'post',function(data){
				if(data.code == 0){
					$scope.getMateriels();
					$scope.newMData = {
						"name": "",
						"category_id": "",
						"material_unit_id": "",
						"workshop_id": "",
						"procedure_id": "",
						"work_time": 0,
						"base_unit_value": 0,
						"detail": [],
						"remarks":'',
						"unit_id":null
					}
					$scope.selectM = []
					$('#newSonM').modal('toggle')					
				}else{
					$scope.showError(data.msg)
				}
			})

		}
		//删除物料
		$scope.delM = function(m){
			$scope.delMData = m
			$('#delM').modal('toggle')
		}
		$scope.sureDelM = function(){
			console.log($scope.delMData.id)
			$scope.getJson($scope.resultPath+'/wisdomeatery/v1/canteens/'+$scope.canteenId+'/processing_materials/'+$scope.delMData.id,'','delete',function(data){
				if(data.code == 0){
					$scope.getMateriels();	
					$('#delM').modal('toggle')
				}else{
					$scope.showError(data.msg)
				}
			})
			
		}
		//编辑物料 
		$scope.editM= function(m){
			var a
			let temp = m
			$scope.staticEditM = {
				"name": m.name,
				"category_id": m.category_id,
				"workshop_id": m.workshop_id,
				"procedure_id": m.procedure_id,
				"work_time": m.work_time,
				"net_ratio": m.net_ratio,
				"detail": m.detail,
				"id":m.id,
				"remarks":m.remarks,
				"category_name":m.category_name,
				"unit_id":m.unit_id
			}
			$scope.editMData = {
				"name": m.name,
				"category_id": m.category_id,
				"workshop_id": m.workshop_id,
				"procedure_id": m.procedure_id,
				"work_time": m.work_time,
				"net_ratio": m.net_ratio,
				"detail": m.detail,
				"id":m.id,
				"remarks":m.remarks,
				"category_name":m.category_name,
				"unit_id":m.unit_id,
				"chef_id":m.chef_id
			}
			console.log(m)
			$scope.getSelectData()
			$scope.textareaData = []
			$scope.selectM = m.detail
			for(let i = 0;i<$scope.selectM.length;i++){
				let name = $scope.selectM[i].material_name
				$scope.textareaData.push(name)
			}
			//请求所有标准成分
			$scope.getAllsons(m.level)
			$('#editSonM').modal('toggle')
		}
		//保存编辑物料
		$scope.saveEditM = function(){
			
			let id = $scope.editMData.id
			delete $scope.editMData.id
			console.log($scope.editMData)
			if($scope.editMData.name == '' ||$scope.editMData.name ==undefined ||$scope.editMData.procedure_id == '' || $scope.editMData.workshop_id == '' ||$scope.editMData.work_time<0 || $scope.editMData.detail == undefined 
				|| $scope.editMData.detail.length<1 || $scope.editMData.work_time == undefined 
				|| $scope.editMData.net_ratio == undefined || $scope.editMData.unit_id == null || $scope.editMData.unit_id ==undefined ){
				$scope.showError('请检查信息完整度')
				return
			}
			$scope.getJson($scope.resultPath+'/wisdomeatery/v1/canteens/'+$scope.canteenId+'/processing_materials/'+id,$scope.editMData,'put',function(data){
				if(data.code == 0){
					$scope.getMateriels()
					$('#editSonM').modal('toggle')
					$scope.showSuccess()
				}else{
					$scope.showError(data.msg)
				}
			})

		}
		//取消编辑物料
		$scope.cancleEditM = function(){
			$scope.editMData = $scope.staticEditM
			$scope.selectM = $scope.staticEditM.detail
		}
//编辑物料标准成分
		//模态框出现后赋予静态不变值
		$("#selectSons").on('shown.bs.modal',function(){
			if($scope.selectM == undefined){
				$scope.staticSelectM = []
			}else{
				$scope.staticSelectM = $scope.selectM.concat()				
			}
		})
		//添加标准成分
		$scope.addM = function(m){
			let flag = 0
			
			if($scope.selectM == undefined){
				$scope.selectM = []
			}
			angular.forEach($scope.selectM, function(data){
				if(data.material_id == m.id){
					flag = 1
				}
			});
			//已选中无此项
			if(flag == 0){
				this.selectM.push({'material_id':m.id,'material_name':m.name,'material_count':'','material_type':m.type})
			}
		}
		//移除标准成分
		$scope.removeM = function(id){
			let arr = $scope.selectM.concat() ;
			for(let i=0; i<arr.length; i++) {
			    if(arr[i].material_id == id) {
			      arr.splice(i, 1);
			      break;
			    }
			  }
			 $scope.selectM = arr.concat() ;
		}
		//将选择的成分填入textarea
		$scope.MToTextarea = function(){
			if($scope.editMData != undefined){
				$scope.editMData.detail = $scope.selectM
			}		
			$scope.textareaData = []
			for(let i = 0;i<$scope.selectM.length;i++){
				//检查是否存在0项
				if($scope.selectM[i].material_count=='0' || $scope.selectM[i].material_count==''){
					$scope.showError('数量必须大于0')
					return
				}
				let name = $scope.selectM[i].material_name
				$scope.textareaData.push(name)
			}
			$('#selectSons').modal('toggle')
		}
		//取消编辑
		$scope.cancleSelectSon = function(){
			$scope.selectM = $scope.staticSelectM
			$('#selectSons').modal('toggle')
		}
		//按类别筛选
		$scope.selectBigCName = '全部类别'
//.................深复制 递归避免复制中的引用
		function copy(p,c){
			var c = c || {}; //最初的时候给它一个初始值=它自己或者是一个json
			for (var i in p) {
			    if (typeof p[i] === 'object') {
			     
			      	c[i] = (p[i].constructor === Array) ? [] : {}; //我们让要复制的对象的name项=数组或者是json
			      	copy(p[i],c[i]); //然后来无限调用函数自己 递归思想
			     
			      
			    }else{
			      c[i] = p[i];  //如果不是对象，直接等于即可，不会发生引用。
			    }
			}
			return c; //然后在把复制好的对象给return出去
		}
//...................................
	}])
	


	.controller('newMaterielCtrl', ['$scope', '$timeout', function($scope, $timeout) {
		console.log(111111)
	}])